package com.iot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.repository.DeviceConfigMapper;
import com.iot.entity.DeviceConfig;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DeviceConfigServiceImpl extends ServiceImpl<DeviceConfigMapper, DeviceConfig> implements DeviceConfigService {

    private final DeviceConfigMapper configMapper;

    @Override
    public void setConfig(String deviceId, String key, String value) {
        LambdaQueryWrapper<DeviceConfig> wrapper = Wrappers.<DeviceConfig>lambdaQuery()
                .eq(DeviceConfig::getDeviceId, deviceId)
                .eq(DeviceConfig::getConfigKey, key);
        Date now = new Date();
        DeviceConfig existing = configMapper.selectOne(wrapper);
        if (existing != null) {
            existing.setConfigValue(value);
            existing.setLastUpdateTime(now);
            configMapper.updateById(existing);
        } else {
            DeviceConfig newConfig = new DeviceConfig();
            newConfig.setDeviceId(deviceId);
            newConfig.setConfigKey(key);
            newConfig.setConfigValue(value);
            newConfig.setStatus("active");
            newConfig.setSource("platform");
            newConfig.setLastUpdateTime(now);
            configMapper.insert(newConfig);
        }
    }

    @Override
    public List<DeviceConfig> getConfigByDevice(String deviceId) {
        return configMapper.selectList(
                Wrappers.<DeviceConfig>lambdaQuery().eq(DeviceConfig::getDeviceId, deviceId)
        );
    }

    @Override
    public void deleteConfig(String deviceId, String key) {
        configMapper.delete(
                Wrappers.<DeviceConfig>lambdaQuery()
                        .eq(DeviceConfig::getDeviceId, deviceId)
                        .eq(DeviceConfig::getConfigKey, key)
        );
    }

    @Override
    public List<DeviceConfig> getPendingConfigs() {
        return configMapper.selectList(
                Wrappers.<DeviceConfig>lambdaQuery()
                        .eq(DeviceConfig::getStatus, "pending")
        );
    }

    @Override
    public void updateConfig(DeviceConfig deviceConfig) {
        deviceConfig.setLastUpdateTime(new Date());
        configMapper.updateById(deviceConfig);
    }


}
